package com.tencent.qf.team.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencent.qf.mybatis.pojo.PageRequest;
import com.tencent.qf.mybatis.pojo.PageResult;
import com.tencent.qf.team.dao.TyOrderDao;
import com.tencent.qf.team.dto.db.GuiderOrderCpsMultiUserstatisticDo;
import com.tencent.qf.team.dto.db.GuiderOrderCpsMultiUserstatisticResDo;
import com.tencent.qf.team.dto.db.GuiderOrderCpsPaginateDo;
import com.tencent.qf.team.dto.db.GuiderOrderCpsPersonalTotalDo;
import com.tencent.qf.team.dto.db.GuiderOrderGoodsCpsPaginateDo;
import com.tencent.qf.team.dto.request.GuiderOrderCpsMultiUserstatisticRequest;
import com.tencent.qf.team.dto.request.GuiderOrderCpsPaginateRequest;
import com.tencent.qf.team.dto.request.GuiderOrderCpsPersonalTotalRequest;
import com.tencent.qf.team.dto.request.GuiderOrderGoodsCpsPaginateRequest;
import com.tencent.qf.team.dto.response.GuiderOrderCpsMultiUserstatisticResponse;
import com.tencent.qf.team.dto.response.GuiderOrderCpsPaginateResponse;
import com.tencent.qf.team.dto.response.GuiderOrderCpsPersonalTotalResponse;
import com.tencent.qf.team.dto.response.GuiderOrderGoodsCpsPaginateResponse;
import com.tencent.qf.team.service.GuiderOrderCpsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class GuiderOrderCpsServiceImpl implements GuiderOrderCpsService {
    @Autowired
    private TyOrderDao tyOrderDao;

    /**
     * 小B(包含下属)维度-个人订单总计
     *
     * @param request
     * @return
     */
    @Override
    public GuiderOrderCpsPersonalTotalResponse guiderOrderCpsPersonalTotal(GuiderOrderCpsPersonalTotalRequest request) {
        GuiderOrderCpsPersonalTotalDo totalDo = new GuiderOrderCpsPersonalTotalDo();
        BeanUtils.copyProperties(request, totalDo);
        if (StringUtils.isNotEmpty(request.getStartDate())) {
            long epochMilli = LocalDateTime.parse(request.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            totalDo.setStartTime(epochMilli);
        }
        if (StringUtils.isNotEmpty(request.getEndDate())) {
            long epochMilli = LocalDateTime.parse(request.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            totalDo.setEndTime(epochMilli);
        }
        GuiderOrderCpsPersonalTotalResponse response = tyOrderDao.guiderOrderCpsPersonalTotal(totalDo);
        return response;
    }

    /**
     * 小B(包含下属)维度订单-分页获取订单明细
     *
     * @param request
     * @return
     */
    @Override
    public PageResult<GuiderOrderCpsPaginateResponse> guiderOrderCpsPaginate(PageRequest<GuiderOrderCpsPaginateRequest> request) {
        GuiderOrderCpsPaginateRequest requestData = request.getData();
        GuiderOrderCpsPaginateDo paginateDo = new GuiderOrderCpsPaginateDo();
        BeanUtils.copyProperties(requestData, paginateDo);
        if (StringUtils.isNotEmpty(requestData.getStartDate())) {
            long epochMilli = LocalDateTime.parse(requestData.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            paginateDo.setStartTime(epochMilli);
        }
        if (StringUtils.isNotEmpty(requestData.getEndDate())) {
            long epochMilli = LocalDateTime.parse(requestData.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            paginateDo.setEndTime(epochMilli);
        }
        if (requestData.getPerformRange() == null) {
            paginateDo.setPerformRange1(1);
            paginateDo.setPerformRange2(1);
            paginateDo.setPerformRange3(1);
        } else {
            for (int performRange : requestData.getPerformRange()) {
                if (performRange == 1) {
                    paginateDo.setPerformRange1(1);
                    continue;
                }
                if (performRange == 2) {
                    paginateDo.setPerformRange2(1);
                    continue;
                }
                if (performRange == 3) {
                    paginateDo.setPerformRange3(1);
                    continue;
                }
            }
        }

        PageHelper.startPage(request.getPageNo(), request.getPageSize());
        List<GuiderOrderCpsPaginateResponse> data = tyOrderDao.guiderOrderCpsPaginate(paginateDo);
        PageInfo<GuiderOrderCpsPaginateResponse> pageInfo = new PageInfo(data);
        return PageResult.build(pageInfo);
    }

    /**
     * 运营平台_小b订单业绩汇总
     *
     * @param request
     * @return
     */
    @Override
    public List<GuiderOrderCpsMultiUserstatisticResponse> guiderOrderCpsMultiUserstatistic(GuiderOrderCpsMultiUserstatisticRequest request) {
        GuiderOrderCpsMultiUserstatisticDo multiUserstatisticDo = new GuiderOrderCpsMultiUserstatisticDo();
        BeanUtils.copyProperties(request, multiUserstatisticDo);

        if (StringUtils.isNotEmpty(request.getStartDate())) {
            long epochMilli = LocalDateTime.parse(request.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            multiUserstatisticDo.setStartTime(epochMilli);
        }
        if (StringUtils.isNotEmpty(request.getEndDate())) {
            long epochMilli = LocalDateTime.parse(request.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            multiUserstatisticDo.setEndTime(epochMilli);
        }
        if (request.getPerformRange() == null) {
            multiUserstatisticDo.setPerformRange1(1);
            multiUserstatisticDo.setPerformRange2(1);
            multiUserstatisticDo.setPerformRange3(1);
        } else {
            for (int performRange : request.getPerformRange()) {
                if (performRange == 1) {
                    multiUserstatisticDo.setPerformRange1(1);
                    continue;
                }
                if (performRange == 2) {
                    multiUserstatisticDo.setPerformRange2(1);
                    continue;
                }
                if (performRange == 3) {
                    multiUserstatisticDo.setPerformRange3(1);
                    continue;
                }
            }
        }
        // 构建默认返回值
        List<GuiderOrderCpsMultiUserstatisticResponse> result = new ArrayList<>();
        for (String uid : request.getCpsuids()) {
            result.add(new GuiderOrderCpsMultiUserstatisticResponse(uid));
        }
        // 查询DB数据
        List<GuiderOrderCpsMultiUserstatisticResDo> data = tyOrderDao.guiderOrderCpsMultiUserstatistic(multiUserstatisticDo);
        if (CollectionUtils.isEmpty(data)) {
            return result;
        }

        Map<String, GuiderOrderCpsMultiUserstatisticResponse> resultMap =
                result.stream().collect(Collectors.toMap(GuiderOrderCpsMultiUserstatisticResponse::getCpsuid, e -> e));
        // 业绩范围 1=自购 2=粉丝购 3=学员购
        data.stream().forEach(e -> {
            // 业绩范围-（1、自购）
            String cpsUid = e.getBuyerinfoCpsUid();
            if (resultMap.containsKey(cpsUid)) {
                GuiderOrderCpsMultiUserstatisticResponse item = resultMap.get(cpsUid);
                item.setGmv(item.getGmv().add(e.getPredictCommissionAmount()));
                item.setOrderCount(item.getOrderCount() + 1);
                item.getUnionIds().add(e.getUnionId());
            }
            // 业绩范围-（2、粉丝购）
            cpsUid = e.getMemberLevel1CpsUid();
            if (resultMap.containsKey(cpsUid)) {
                GuiderOrderCpsMultiUserstatisticResponse item = resultMap.get(cpsUid);
                item.setGmv(item.getGmv().add(e.getPredictCommissionAmount()));
                item.setOrderCount(item.getOrderCount() + 1);
                item.getUnionIds().add(e.getUnionId());
            }
            // 业绩范围-（3、学员购）
            cpsUid = e.getMemberLevel2CpsUid();
            if (resultMap.containsKey(cpsUid)) {
                GuiderOrderCpsMultiUserstatisticResponse item = resultMap.get(cpsUid);
                item.setGmv(item.getGmv().add(e.getPredictCommissionAmount()));
                item.setOrderCount(item.getOrderCount() + 1);
                item.getUnionIds().add(e.getUnionId());
            }
        });
        // 数据汇总
        for (Map.Entry<String, GuiderOrderCpsMultiUserstatisticResponse> entry : resultMap.entrySet()) {
            GuiderOrderCpsMultiUserstatisticResponse item = entry.getValue();
            item.setBuyerCount(item.getUnionIds().size());
            item.setUnionIds(null);
            if (request.getUnit() == 1) {
                // 元
                item.setGmv(item.getGmv().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
            }
            if (item.getBuyerCount() != 0) {
                item.setAtv(item.getGmv().divide(new BigDecimal(item.getBuyerCount()), 2, RoundingMode.HALF_UP));
            }
        }

        return result;
    }

    /**
     * 小B(包含下属)维度-订单商品分页
     *
     * @param request
     * @return
     */
    @Override
    public PageResult<GuiderOrderGoodsCpsPaginateResponse> guiderOrderGoodsCpsPaginate(PageRequest<GuiderOrderGoodsCpsPaginateRequest> request) {
        GuiderOrderGoodsCpsPaginateRequest requestData = request.getData();
        GuiderOrderGoodsCpsPaginateDo paginateDo = new GuiderOrderGoodsCpsPaginateDo();
        BeanUtils.copyProperties(requestData, paginateDo);
        if (StringUtils.isNotEmpty(requestData.getStartDate())) {
            long epochMilli = LocalDateTime.parse(requestData.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            paginateDo.setStartTime(epochMilli);
        }
        if (StringUtils.isNotEmpty(requestData.getEndDate())) {
            long epochMilli = LocalDateTime.parse(requestData.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
            paginateDo.setEndTime(epochMilli);
        }

        if (requestData.getPerformRange() == null) {
            paginateDo.setPerformRange1(1);
            paginateDo.setPerformRange2(1);
            paginateDo.setPerformRange3(1);
            paginateDo.setPerformRange4(1);
            paginateDo.setPerformRange5(1);
        } else {
            for (int performRange : requestData.getPerformRange()) {
                if (performRange == 1) {
                    paginateDo.setPerformRange1(1);
                    continue;
                }
                if (performRange == 2) {
                    paginateDo.setPerformRange2(1);
                    continue;
                }
                if (performRange == 3) {
                    paginateDo.setPerformRange3(1);
                    continue;
                }
            }
        }

        PageHelper.startPage(request.getPageNo(), request.getPageSize());
        List<GuiderOrderGoodsCpsPaginateResponse> data = tyOrderDao.guiderOrderGoodsCpsPaginate(paginateDo);
        PageInfo<GuiderOrderGoodsCpsPaginateResponse> pageInfo = new PageInfo(data);
        return PageResult.build(pageInfo);
    }
}
